package com.ec.mn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ec.mn.entity.HealthRecord;
import com.ec.mn.entity.WarningRules;
import com.ec.mn.mapper.WarningRulesMapper;
import com.ec.mn.service.WarningRulesService;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WarningRulesServiceImpl extends ServiceImpl<WarningRulesMapper, WarningRules> implements WarningRulesService {
    
    @Override
    public WarningRules getActiveRuleByRecordType(String recordType) {
        return this.getOne(new QueryWrapper<WarningRules>()
                .eq("record_type", recordType)
                .eq("status", 1)
                .last("limit 1"));
    }

    @Override
    public List<WarningRules> getAllActiveRules() {
        return this.list(new QueryWrapper<WarningRules>().eq("status", 1));
    }
    @Override
    public String buildWarningMessage(HealthRecord record) {
        StringBuilder sb = new StringBuilder();
        sb.append("健康预警:");
        sb.append("老人ID: ").append(record.getElderlyUserId()).append("，");
        sb.append(record.getRecordType()).append("异常！ \n");
        sb.append("测量值：").append(record.getValue1());
        if (record.getValue2() != null && !record.getValue2().isEmpty()) {
            sb.append("/").append(record.getValue2());
        }
        if (record.getUnit() != null) {
            sb.append(" ").append(record.getUnit());
        }
        sb.append(" \n");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        sb.append("测量时间：").append(record.getRecordedAt().format(formatter)).append(" \n");
        if (record.getNotes() != null && !record.getNotes().isEmpty()) {
            sb.append("备注：").append(record.getNotes()).append(" \n");
        }
        String ruleDescription =getActiveRuleByRecordType(record.getRecordType()).getDescription();
        if (ruleDescription != null && !ruleDescription.isEmpty()) {
            sb.append("预警规则：").append(ruleDescription).append(" \n");
        }
        sb.append("请及时关注老人健康状况。");
        return sb.toString();
    }
    @Override
    public String checkAndWarn(HealthRecord healthRecord) {
        // 1. 查询对应的启用规则
        WarningRules rule = getActiveRuleByRecordType(healthRecord.getRecordType());
        if (rule == null) {
            healthRecord.setIsAbnormal(0); // 没有规则，视为正常
            return null;
        }

        int isAbnormal =0;

        // 检查 value1
        if (rule.getMinValue1() != null && !rule.getMinValue1().isEmpty()) {
            try {
                if (Double.parseDouble(healthRecord.getValue1()) < Double.parseDouble(rule.getMinValue1())) {
                    isAbnormal = 1;
                }
            } catch (Exception ignored) {}
        }
        if (rule.getMaxValue1() != null && !rule.getMaxValue1().isEmpty()) {
            try {
                if (Double.parseDouble(healthRecord.getValue1()) > Double.parseDouble(rule.getMaxValue1())) {
                    isAbnormal = 1;
                }
            } catch (Exception ignored) {}
        }

        // 检查 value2（如有）
        if (healthRecord.getValue2() != null) {
            if (rule.getMinValue2() != null && !rule.getMinValue2().isEmpty()) {
                try {
                    if (Double.parseDouble(healthRecord.getValue2()) < Double.parseDouble(rule.getMinValue2())) {
                        isAbnormal = 1;
                    }
                } catch (Exception ignored) {}
            }
            if (rule.getMaxValue2() != null && !rule.getMaxValue2().isEmpty()) {
                try {
                    if (Double.parseDouble(healthRecord.getValue2()) > Double.parseDouble(rule.getMaxValue2())) {
                        isAbnormal = 1;
                    }
                } catch (Exception ignored) {}
            }
        }

        // 3. 处理预警
        if (isAbnormal==1) {
            healthRecord.setIsAbnormal(1);
            return buildWarningMessage(healthRecord);
        } else {
            healthRecord.setIsAbnormal(0);
            return null;
        }
    }

    @Override
    public List<String> getAllRecordTypes() {
        List<WarningRules> list = this.list();
        // 只取recordType字段
        return list.stream()
                .map(WarningRules::getRecordType)
                .collect(Collectors.toList());
    }
} 